package suzf.top.mall.ui.activity

import android.os.Bundle
import android.support.v4.app.Fragment
import com.ashokvarma.bottomnavigation.BottomNavigationBar
import kotlinx.android.synthetic.main.activity_main.*
import suzf.top.base.ui.activity.BaseActivity
import suzf.top.goodscenter.ui.fragment.CategoryFragment
import suzf.top.mall.R
import suzf.top.mall.ui.fragment.HomeFragment
import suzf.top.mall.ui.fragment.MeFragment
import java.util.*

class MainActivity: BaseActivity() {

    private val mStack = Stack<Fragment>()

    private val mHomeFragment by lazy { HomeFragment() }
    private val mCategoryFragment by lazy { CategoryFragment() }
    private val mCartFragment by lazy { HomeFragment() }
    private val mMsgFragment by lazy { HomeFragment() }
    private val mMeFragment by lazy { MeFragment() }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

       // initView()
        initFragment()
        initButtonNav()
        changeFragment(0)
    }

    /**
     *  初始化视图
     */
    private fun initView() {
        val fragmentManger = supportFragmentManager.beginTransaction()
        fragmentManger.replace(R.id.mContaier,HomeFragment())
        fragmentManger.commit()
    }


    private fun initFragment() {

        val fragmentManger = supportFragmentManager.beginTransaction()
        fragmentManger.add(R.id.mContaier,mHomeFragment)
        fragmentManger.add(R.id.mContaier,mCategoryFragment)
        fragmentManger.add(R.id.mContaier,mCartFragment)
        fragmentManger.add(R.id.mContaier,mMsgFragment)
        fragmentManger.add(R.id.mContaier,mMeFragment)
        fragmentManger.commit()

        mStack.add(mHomeFragment)
        mStack.add(mCategoryFragment)
        mStack.add(mCartFragment)
        mStack.add(mMsgFragment)
        mStack.add(mMeFragment)
    }

    private fun initButtonNav() {
        mBottomNavBar.setTabSelectedListener(object: BottomNavigationBar.OnTabSelectedListener{
            override fun onTabReselected(position: Int) {
            }

            override fun onTabUnselected(position: Int) {
            }

            override fun onTabSelected(position: Int) {
                changeFragment(position)
            }

        })
    }

    /*
        切换fragment
     */
    private fun  changeFragment(position: Int) {
        val fragmentManger = supportFragmentManager.beginTransaction()
        for (fragment in mStack) {
            fragmentManger.hide(fragment)
        }
        fragmentManger.show(mStack[position])
        fragmentManger.commit()
    }
}
